<template>
  <div class="userSelector">
    <el-row :gutter="12">
      <el-col :span="4">
        <TreeFilter
          ref="treeFilterRef"
          label="orgName"
          :title="$t('message.orgInfo.title')"
          :data="orgSelectorData"
          :default-expand="props.defaultExpand"
          @change="handleChange"
        >
        </TreeFilter>
      </el-col>
      <el-col :span="10" class="table">
        <ProTable
          ref="userTableRef"
          :request-api="userApi.userSelector"
          :columns="columns"
          :tool-button="false"
          :init-param="initParam"
          :data-callback="dataCallback"
          :request-auto="false"
        >
          <template #operation="scope">
            <el-button type="primary" link :icon="CirclePlus" plain @click="addChooseUser(scope.row)">
              {{ $t("message.commonBtn.add") }}
            </el-button>
          </template>
        </ProTable>
      </el-col>
      <el-col :span="10" class="table">
        <ProTable
          ref="chooseTableRef"
          :data="props.chooseData"
          :columns="columns"
          :tool-button="false"
          @search="refreshChoosedUser"
          @reset="resetChoosedUser"
        >
          <template #operation="scope">
            <el-button type="primary" link :icon="Delete" plain @click="removeUser(scope.row)">
              {{ $t("message.commonBtn.delete") }}
            </el-button>
          </template>
        </ProTable>
      </el-col>
    </el-row>
  </div>
</template>
<script setup lang="ts" name="UserSelector">
import TreeFilter from "@/components/TreeFilter/index.vue";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps, ProTableInstance } from "../ProTable/interface";
import userApi from "@/api-services/apis/system/userApi";
import { useOrgStore } from "@/stores/modules/org";
import { SysOrg, SysUser } from "@/api-services/models/system";
import { CirclePlus, Delete } from "@element-plus/icons-vue";
import { SqlSugarPagedList, UnifyResult } from "@/api-services/unifyResult";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const treeFilterRef = ref<InstanceType<typeof TreeFilter> | null>(null);
const userTableRef = ref<ProTableInstance>();
const chooseTableRef = ref<ProTableInstance>();
const orgSelectorData = ref<SysOrg.OrgSimpleInfo[]>();
const orgStore = useOrgStore();
const initParam = reactive({ orgId: 0, keyWord: "" });
const choosedUser = ref<SysUser.UserSimpleInfo[]>([]);
interface UserSelectorProps {
  defaultExpand?: boolean; //是否展开
  chooseData?: SysUser.UserSimpleInfo[];
}
const props = ref<UserSelectorProps>({
  defaultExpand: false
});
const dataCallback = (queryRes: UnifyResult<SqlSugarPagedList<SysUser.UserSimpleInfo>>) => {
  const data = queryRes.data;
  return {
    items: data.items,
    totalCount: data.totalCount,
    pageIndex: data.pageIndex,
    pageSize: data.pageSize
  };
};
const columns: ColumnProps<SysUser.UserSimpleInfo>[] = [
  { prop: "account", label: t("message.sysUser.account"), search: { key: "keyword", el: "input", span: 2 } },
  { prop: "name", label: t("message.sysUser.name") },
  { prop: "operation", label: t("message.commonBtn.oper"), width: 80, fixed: "left" }
];
const handleChange = (val: number) => {
  userTableRef.value!.pageable.pageIndex = 1;
  initParam.orgId = val;
};
const queryUser = () => {
  userTableRef.value?.getTableList();
};

const refreshChoosedUser = () => {
  let keyword = chooseTableRef.value?.searchParam?.keyword;
  if (keyword) {
    props.value.chooseData = choosedUser.value.filter(item => {
      return item.account!.indexOf(keyword) > -1 || item.name!.indexOf(keyword) > -1;
    });
    setTimeout(() => {
      chooseTableRef.value?.refreshTable();
    }, 10);
  }
};
const resetChoosedUser = () => {
  props.value.chooseData = choosedUser.value;
  setTimeout(() => {
    chooseTableRef.value?.refreshTable();
  }, 10);
};
const addChooseUser = (user: SysUser.UserSimpleInfo) => {
  let index = choosedUser.value.findIndex((item: SysUser.UserSimpleInfo) => item.id == user.id);
  if (index == -1) choosedUser.value.push(user);
  chooseTableRef.value?.refreshTable();
};
const removeUser = (user: SysUser.UserSimpleInfo) => {
  const index = choosedUser.value.findIndex((item: SysUser.UserSimpleInfo) => item.id == user.id);
  if (index !== -1) {
    choosedUser.value.splice(index, 1);
    chooseTableRef.value?.refreshTable();
  }
};

const useUserSelector = async (param: UserSelectorProps) => {
  queryUser();
  props.value = param;
  orgSelectorData.value = await orgStore.orgSelectorGet;
  choosedUser.value = props.value.chooseData ?? [];
  resetChoosedUser();
};
const getChoosedUser = () => {
  return choosedUser.value;
};
defineExpose({ useUserSelector, getChoosedUser });
</script>
<style lang="scss" scoped>
.align-container {
  display: flex;
  align-items: center; /* 垂直居中 */
}
.userSelector {
  :deep(.table-main) {
    height: 520px;
    max-height: 520px !important;
  }
  :deep(.filter) {
    height: 600px;
    max-height: 600px !important;
  }
  .table {
    :deep(.card) {
      padding-bottom: 5px;
      margin-bottom: 5px;
    }
  }
  :deep(.el-scrollbar__bar.is-vertical) {
    display: block !important;
  }
}
</style>
